import * as fs from 'fs'
import * as path from 'path'
import * as http from 'http'
const COS = require('cos-nodejs-sdk-v5')
const cos = new COS({
  SecretId: 'AKID7CEJIPZrMrJkGxVUSUzu6dE1QuhVIY8z', // 推荐使用环境变量获取；用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
  SecretKey: 'njDNYB28OftBKQpN8nPF4timryEUl4Rx' // 推荐使用环境变量获取；用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
})

export async function downloadAndUploadImg(url: string): Promise<string> {
  return new Promise((resolve, reject) => {
    if (!url) {
      console.log('No URL')
      return reject()
    }
    const cardImgPath = url.split('/')
    const fileName = cardImgPath.pop()?.split('?')[0] + '.jpg'
    const localPath = path.join('assets')
    const prepareFinish = fs.existsSync(localPath)
    if (!prepareFinish) {
      fs.mkdirSync(localPath, { recursive: true })
    }
    const localFile = path.join(localPath, fileName!)
    if (fs.existsSync(localFile)) {
      console.log('File Exist')
      return reject()
    }
    // download file
    try {
      console.log('Downloading:', url)
      const writeStream = fs.createWriteStream(localFile)
      http.get(url.replace('https', 'http'), (response) => {
        response.pipe(writeStream)
        writeStream.on('finish', async () => {
          writeStream.close()
          console.log('Download Completed')
          const Key = `info/${fileName}`
          cos.putObject(
            {
              Bucket: 'uazh-1258961180', // 必须
              Region: 'ap-nanjing', // 存储桶所在地域，必须字段
              Key, // 必须
              StorageClass: 'STANDARD',
              Body: fs.readFileSync(localFile) // 上传文件对象
            },
            (err) => {
              if (err) {
                console.log(err)
                return reject()
              } else {
                return resolve(Key)
              }
            }
          )
        })
      })
    } catch (error) {
      console.log(error)
      return reject()
    }
  })
}
